<template>
  <div class="view">
    <Panel :title="$t('m.Student_Student') ">
      <div slot="header">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-button v-show="selectedStudents.length"
                       type="warning" icon="el-icon-fa-trash"
                       @click="deleteStudents(selectedStudentIDs)">Delete
            </el-button>
          </el-col>
          <el-col :span="selectedStudents.length ? 16: 24">
            <el-input v-model="keyword" prefix-icon="el-icon-search" placeholder="Keywords"></el-input>
          </el-col>
        </el-row>
      </div>
      <el-table
        v-loading="loadingTable"
        element-loading-text="loading"
        @selection-change="handleSelectionChange"
        ref="table"
        :data="studentList"
        style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column prop="id" label="ID"></el-table-column>

        <el-table-column prop="username" label="学号"></el-table-column>

        <el-table-column prop="real_name" label="姓名"></el-table-column>

        <el-table-column prop="grade" label="年级"></el-table-column>

        <el-table-column prop="major" label="专业"></el-table-column>

        <el-table-column prop="classes" label="班级"></el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="{row}">
            <icon-btn name="Edit" icon="edit" @click.native="openStudentDialog(row.id)"></icon-btn>
            <icon-btn name="Delete" icon="trash" @click.native="deleteStudents([row.id])"></icon-btn>
          </template>
        </el-table-column>
      </el-table>
      <div class="panel-options">
        <el-button size="small" type="primary" @click="openStudentDialog (null)">{{$t('m.Create_Student')}}</el-button>
        <el-pagination
          class="page"
          layout="prev, pager, next"
          @current-change="currentChange"
          :page-size="pageSize"
          :total="total">
        </el-pagination>
      </div>
    </Panel>

    <Panel>
      <span slot="title">{{$t('m.Import_Student')}}
        <el-popover placement="right" trigger="hover">
          <p>只支持没有表头的CSV文件，格式为：学号，密码，邮箱，姓名，年级，专业，班级</p>
          <p>示例：20200121004,user123,yi@qq.com,张一,2021,软件技术,1</p>
          <a href="/static/downloadable/students.csv" >点击下载示例文件</a>
          <i slot="reference" class="el-icon-fa-question-circle import-user-icon"></i>
        </el-popover>
      </span>
      <el-upload v-if="!uploadStudents.length"
                 action=""
                 :show-file-list="false"
                 accept=".csv"
                 :before-upload="handleStudentsCSV">
        <el-button size="small" icon="el-icon-fa-upload" type="primary">选择文件</el-button>
      </el-upload>
      <template v-else>
        <el-table :data="uploadStudentsPage">
          <el-table-column label="学号">
            <template slot-scope="{row}">
              {{row[0]}}
            </template>
          </el-table-column>
          <el-table-column label="姓名">
            <template slot-scope="{row}">
              {{row[3]}}
            </template>
          </el-table-column>
          <el-table-column label="密码">
            <template slot-scope="{row}">
              {{row[1]}}
            </template>
          </el-table-column>
          <el-table-column label="邮箱">
            <template slot-scope="{row}">
              {{row[2]}}
            </template>
          </el-table-column>
          <el-table-column label="年级">
            <template slot-scope="{row}">
              {{row[4]}}
            </template>
          </el-table-column>
          <el-table-column label="专业">
            <template slot-scope="{row}">
              {{row[5]}}
            </template>
          </el-table-column>
          <el-table-column label="班级">
            <template slot-scope="{row}">
              {{row[6]}}
            </template>
          </el-table-column>
        </el-table>
        <div class="panel-options">
          <el-button type="primary" size="small"
                     icon="el-icon-fa-upload"
                     @click="handleStudentsUpload">Import All
          </el-button>
          <el-button type="warning" size="small"
                     icon="el-icon-fa-undo"
                     @click="handleResetData">Reset Data
          </el-button>
          <el-pagination
            class="page"
            layout="prev, pager, next"
            :page-size="uploadStudentsPageSize"
            :current-page.sync="uploadStudentsCurrentPage"
            :total="uploadStudents.length">
          </el-pagination>
        </div>
      </template>
    </Panel>

    <!--对话框-->
    <el-dialog :title="$t('m.Student_Info')" :visible.sync="showStudentDialog" :close-on-click-modal="false">
      <el-form :model="student" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('m.Student_Username')" required>
              <el-input v-model="student.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.Student_Real_Name')" required>
              <el-input v-model="student.real_name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.Student_Email')" required>
              <el-input v-model="student.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.Student_Grade')" required>
              <el-select v-model="student.grade">
                <el-option v-for="item in this.gradeOptions" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.Student_Major')" required>
              <el-select v-model="student.major">
                <el-option v-for="item in this.majorOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('m.Student_Class')" required>
              <el-select v-model="student.classes">
                <el-option v-for="item in this.classOptions" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="this.editInfo == true">
            <el-form-item :label="$t('m.Two_Factor_Auth')">
              <el-switch
                v-model="student.two_factor_auth"
                :disabled="!student.real_tfa"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="this.editInfo == true">
            <el-form-item label="Open Api">
              <el-switch
                v-model="student.open_api"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="this.editInfo == true">
            <el-form-item :label="$t('m.Is_Disabled')">
              <el-switch
                v-model="student.is_disabled">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="this.editInfo == true">
            <el-form-item label="是否重置密码">
              <el-switch
                v-model="resetPassword">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <p style='color:red;' v-if="this.editInfo == false">初始密码为：user123，请通知用户尽快更换为自己的密码</p>
      <span slot="footer" class="dialog-footer">
        <cancel @click.native="showStudentDialog = false">Cancel</cancel>
        <save @click.native="saveStudent()"></save>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import papa from 'papaparse'
  import api from '../../api.js'

  export default {
    name: 'Student',
    data () {
      return {
        // 一页显示的用户数
        pageSize: 10,
        // 用户总数
        total: 0,
        // 用户列表
        studentList: [],
        uploadStudents: [],
        uploadStudentsPage: [],
        uploadStudentsCurrentPage: 1,
        uploadStudentsPageSize: 15,
        // 搜索关键字
        keyword: '',
        // 是否显示用户对话框
        showStudentDialog: false,
        // 当前用户model
        student: {},
        loadingTable: false,
        // 当前页码
        currentPage: 0,
        selectedStudents: [],
        editInfo: true,
        resetPassword: false,
        gradeOptions: [],
        classOptions: new Array(15).fill(null).map((_, i) => i + 1),
        majorOptions: [{label: '软件技术', value: '软件技术'}, {label: '移动应用开发', value: '移动应用开发'}, {label: '计算机应用技术', value: '计算机应用技术'}, {label: '大数据技术与应用', value: '大数据技术与应用'}, {label: '云计算技术与应用', value: '云计算技术与应用'}]
      }
    },

    mounted () {
      this.getStudentList(1)
      const y = (new Date()).getFullYear() - 3
      this.gradeOptions = new Array(4).fill(null).map((_, i) => i + y)
    },

    methods: {
      getStudentList (page) {
        this.loadingTable = true
        // api get students info
        api.getStudentList((page - 1) * this.pageSize, this.pageSize, this.keyword, 'Regular User').then(res => {
          this.loadingTable = false
          this.total = res.data.data.total
          this.studentList = res.data.data.results
          this.studentList.forEach((val, idx) => {
            val.username = val.user.username
            val.id = val.user.id
          })
        }, res => {
          this.loadingTable = false
        })
      },
      saveStudent () {
        // 修改学生信息
        if (this.student.id) {
          if (this.resetPassword) {
            this.student.password = 'user123'
          }
          // api editStudent
          api.editStudent(this.student).then(res => {
            // 更新列表
            this.getStudentList(this.currentPage)
          }).then(() => {
            this.showStudentDialog = false
            this.resetPassword = false
          }).catch(() => {
          })
        } else {
          // 新建学生信息
          let uploadAStd = {users: [[this.student.username, 'user123', this.student.email, this.student.real_name, this.student.grade, this.student.major, this.student.classes]]}
          // api createStudent
          api.createStudent(uploadAStd).then(res => {
            // 更新列表
            this.getStudentList(this.currentPage)
          }).then(() => {
            this.showStudentDialog = false
          }).catch(() => {
          })
        }
      },
      handleStudentsCSV (file) {
        papa.parse(file, {
          complete: (results) => {
            let data = results.data.filter(student => {
              return student[0] && student[1] && student[2] && student[3] && student[4] && student[5] && student[6]
            })
            let delta = results.data.length - data.length
            if (delta > 0) {
              this.$warning(delta + ' students have been filtered due to empty value')
            }
            this.uploadStudentsCurrentPage = 1
            this.uploadStudents = data
            this.uploadStudentsPage = data.slice(0, this.uploadStudentsPageSize)
          },
          error: (error) => {
            this.$error(error)
          }
        })
      },
      handleResetData () {
        this.uploadStudents = []
      },
      handleStudentsUpload () {
        let uploadstu = {'users': this.uploadStudents}
        // api importStudents
        api.importStudents(uploadstu).then(res => {
          this.getStudentList(1)
          this.handleResetData()
        })
      },
      openStudentDialog (id) {
        if (id) {
          // 修改学生信息
          this.editInfo = true
          // api getuser by id
          api.getUser(id).then(res => {
            this.student = res.data.data
            this.student.two_factor_auth = this.student.user.two_factor_auth
            this.student.username = this.student.user.username
            this.student.email = this.student.user.email
            this.student.admin_type = this.student.user.admin_type
            this.student.problem_permission = this.student.user.problem_permission
            this.student.open_api = this.student.user.open_api
            this.student.user_id = this.student.user.id
          })
        } else {
          // 创建学生
          this.editInfo = false
          this.student = {}
        }
        this.showStudentDialog = true
      },
      deleteStudents (ids) {
        this.$confirm('Sure to delete the student? The associated resources created by this user will be deleted as well, like problem, contest, announcement, etc.', 'confirm', {
          type: 'warning'
        }).then(() => {
          // api delete user by id
          api.deleteUsers(ids.join(',')).then(res => {
            this.getStudentList(this.currentPage)
          }).catch(() => {
            this.getStudentList(this.currentPage)
          })
        }, () => {
        })
      },
      handleSelectionChange (val) {
        this.selectedStudents = val
      },
      currentChange (page) {
        this.currentPage = page
        this.getStudentList(page)
      }
    },
    computed: {
      selectedStudentIDs () {
        let ids = []
        for (let student of this.selectedStudents) {
          ids.push(student.id)
        }
        return ids
      }
    },
    watch: {
      'keyword' () {
        this.currentChange(1)
      },
      'uploadStudentsCurrentPage' (page) {
        this.uploadStudentsPage = this.uploadStudents.slice((page - 1) * this.uploadStudentsPageSize, page * this.uploadStudentsPageSize)
      }
    }
}
</script>

<style>
</style>